package com.yanqu.road.dao.impl.cross;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.db.DbParameter;
import com.yanqu.road.dao.impl.TempDao;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.rank.cross.CrossUserRank;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class CrossRankDaoImpl extends TempDao {

    public Map<Long, Map<Integer, Map<Integer, LinkedList<CrossUserRank>>>> getCrossUserRankListMap() {
        String sql = "select * from t_c_rank";
        ResultSet rs = null;
        CallableStatement call = null;
        Map<Long, Map<Integer, Map<Integer, LinkedList<CrossUserRank>>>> dataMap = new ConcurrentHashMap<>();
        try {
            getDb().setConnName(DbNameStrategy.getCrossDb());
            call = getDb().getConnection().prepareCall(sql);
            rs = call.executeQuery();
            while (rs.next()) {
                CrossUserRank data = initCrossUserRank(rs);
                Map<Integer, Map<Integer, LinkedList<CrossUserRank>>> tempMap = dataMap.get(data.getUserBaseInfo().getServerId());
                if(null == tempMap){
                    tempMap = new ConcurrentHashMap<>();
                    dataMap.put(data.getUserBaseInfo().getServerId(), tempMap);
                }
                if (!tempMap.containsKey(data.getBigRankType())) {
                    tempMap.put(data.getBigRankType(), new ConcurrentHashMap<>());
                }
                if(!tempMap.get(data.getBigRankType()).containsKey(data.getType())){
                    tempMap.get(data.getBigRankType()).put(data.getType(), new LinkedList<>());
                }
                tempMap.get(data.getBigRankType()).get(data.getType()).add(data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataMap;
    }

    public boolean updateCrossUserRankList(long serverId, List<CrossUserRank> rankList) {
        String sql = "REPLACE INTO t_c_rank(serverId,type,rank,userId,userBaseInfo,lastUpdateTime,value,bigRankType,param,isDelete) VALUES(?,?,?,?,?,?,?,?,?,?)";
        try {
            getDb().setConnName(DbNameStrategy.getCrossDb());
            List<Map<Integer, DbParameter>> mapList = new ArrayList<>();
            int rank = 1;
            for (CrossUserRank userRank : rankList) {
                int i = 1;
                Map<Integer, DbParameter> para = new HashMap<>();
                para.put(i++, new DbParameter(Types.BIGINT, serverId));
                para.put(i++, new DbParameter(Types.INTEGER, userRank.getType()));
                para.put(i++, new DbParameter(Types.INTEGER, rank));
                para.put(i++, new DbParameter(Types.BIGINT, userRank.getUserId()));
                para.put(i++, new DbParameter(Types.NVARCHAR, userRank.getUserBaseInfoJsonStr()));
                para.put(i++, new DbParameter(Types.BIGINT, userRank.getLastUpdateTime()));
                para.put(i++, new DbParameter(Types.VARCHAR, userRank.getValue().toString()));
                para.put(i++, new DbParameter(Types.INTEGER, userRank.getBigRankType()));
                para.put(i++, new DbParameter(Types.VARCHAR, userRank.getParam()));
                para.put(i++, new DbParameter(Types.BOOLEAN, userRank.isDelete()));
                mapList.add(para);
                rank++;
            }
            if (getDb().executeBatchQuery(sql, mapList) > -1) {
                return true;
            }
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        }
        return false;
    }

    private CrossUserRank initCrossUserRank(ResultSet rs) throws SQLException {
        CrossUserRank data = new CrossUserRank();
        data.setParam(rs.getString("param"));
        data.setBigRankType(rs.getInt("bigRankType"));
        data.setType(rs.getInt("type"));
        data.setRank(rs.getInt("rank"));
        data.setUserId(rs.getLong("userId"));
        String baseUserInfoStr = rs.getString("userBaseInfo");
        if(null == baseUserInfoStr){
            baseUserInfoStr = "";
        }
        UserBaseInfo userBaseInfo = JSON.parseObject(baseUserInfoStr, new TypeReference<UserBaseInfo>() {});
        if(null != userBaseInfo){
            data.setUserBaseInfo(userBaseInfo);
        }
        data.setLastUpdateTime(rs.getLong("lastUpdateTime"));
        String value = rs.getString("value");
        if(!StringUtils.isNullOrEmpty(value)) {
            data.setValue(new BigInteger(value));
        }
        data.setDelete(rs.getBoolean("isDelete"));
        return data;
    }
}
